package cn.edu.scnu.semart.user.service.impl;

import cn.edu.scnu.semart.model.user.UserFollow;
import cn.edu.scnu.semart.user.mapper.UserFollowMapper;
import cn.edu.scnu.semart.user.service.UserFollowService;
import cn.edu.scnu.semart.vo.user.FollowUserVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserFollowServiceImpl
        extends ServiceImpl<UserFollowMapper, UserFollow>
        implements UserFollowService {

    @Override
    public boolean follow(Integer followerId, Integer followedId) {
        if (followerId.equals(followedId)) return false; // 不能关注自己
        // 幂等：已存在就返回 true
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowerId, followerId)
                .eq(UserFollow::getFollowedId, followedId);
        if (count(wrapper) > 0) return true;

        UserFollow uf = new UserFollow();
        uf.setFollowerId(followerId);
        uf.setFollowedId(followedId);
        return save(uf);
    }

    @Override
    public boolean unfollow(Integer followerId, Integer followedId) {
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowerId, followerId)
                .eq(UserFollow::getFollowedId, followedId);
        return remove(wrapper);
    }

    @Override
    public boolean isFollow(Integer followerId, Integer followedId) {
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowerId, followerId)
                .eq(UserFollow::getFollowedId, followedId);
        return count(wrapper) > 0;
    }

    @Override
    public long countFans(Integer userId) {
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowedId, userId);
        return count(wrapper);
    }

    @Override
    public long countFollows(Integer userId) {
        LambdaQueryWrapper<UserFollow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollow::getFollowerId, userId);
        return count(wrapper);
    }

    @Override
    public IPage<FollowUserVo> pageFollows(Page<FollowUserVo> page, Integer currentUserId) {
        return baseMapper.pageFollows(page,currentUserId);
    }

    @Override
    public IPage<FollowUserVo> pageFans(Page<FollowUserVo> page, Integer currentUserId) {
        return baseMapper.pageFans(page,currentUserId);
    }
}